package com.yzx.lifeassistants.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.poi.PoiSortType;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.BounceEnter.BounceTopEnter;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.MaterialDialog;
import com.flyco.dialog.widget.NormalListDialog;
import com.yalantis.contextmenu.lib.ContextMenuDialogFragment;
import com.yalantis.contextmenu.lib.MenuObject;
import com.yalantis.contextmenu.lib.MenuParams;
import com.yalantis.contextmenu.lib.interfaces.OnMenuItemClickListener;
import com.yzx.lifeassistants.R;
import com.yzx.lifeassistants.adapter.MyDialogAdapter;
import com.yzx.lifeassistants.base.BaseActivity;
import com.yzx.lifeassistants.utils.ToastUtils;
import com.yzx.lifeassistants.view.bdmap.MyOverlayManager;
import com.yzx.lifeassistants.view.widget.CircularLoadingDialog;

/**
 * @Description: 附近美食
 * @author: yzx
 * @time: 2016-3-7 下午1:27:01
 */
@SuppressLint("InflateParams")
public class FoodActivity extends BaseActivity implements OnClickListener,
		OnGetPoiSearchResultListener, OnMenuItemClickListener {
	private RelativeLayout topRL;// 顶部
	private ImageButton backBtn;// 返回按钮
	private ImageButton moreBtn;// 更多按钮
	private MapView mMapView;// 百度底图

	private BaiduMap mBaiduMap;// 百度地图
	private LocationClient mLocationClient;// 定位
	private BDLocationListener mListener;// 定位监听
	private PoiSearch mPoiSearch;// POI搜索

	private int mPage;// 第几页
	private int totalPage;// 总的几页
	private String mKeyWord;// 搜索关键词
	private int mRadius;// 半径距离
	private int mpageCapacity;// 每页数据量
	private Boolean isFirstLoc;// 是否第一次定位
	private LatLng mLatLng;// 定位结果

	private CircularLoadingDialog dialog;// 加载框
	private MyOverlayManager manager;//
	private List<PoiInfo> poiInfos;// 搜索结果
	private TextView markTV;// Poi标记
	private Marker lastMarker;// 上次点击的标记

	private FragmentManager fragmentManager;//
	private ContextMenuDialogFragment mMenuDialogFragment;//
	private int topHeight;// 顶部高度
	private MenuObject radiusMenu;//
	private NormalListDialog radioDialog;// 半径弹框
	private List<String> radioList;// 半径列表

	private PoiInfo poiInfo;// 点击的Poi信息
	private MaterialDialog poiDialog;// Poi信息弹框

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_food);
		initView();
		setListener();
		initData();
		initMenuFragment();
		initDialog();
		initMap();
	}

	/**
	 * 
	 * @Description: 初始化控件
	 */
	private void initView() {
		topRL = (RelativeLayout) findViewById(R.id.food_top_rl);
		backBtn = (ImageButton) findViewById(R.id.food_back_btn);
		moreBtn = (ImageButton) findViewById(R.id.food_more_btn);
		mMapView = (MapView) findViewById(R.id.food_bmapView);
	}

	/**
	 * 
	 * @Description: 设置监听
	 */
	private void setListener() {
		backBtn.setOnClickListener(this);
		moreBtn.setOnClickListener(this);
	}

	/**
	 * 
	 * @Description: 初始化数据
	 */
	private void initData() {
		dialog = new CircularLoadingDialog(this);
		isFirstLoc = true;
		mPage = 0;
		mKeyWord = "美食";
		mRadius = 500;
		mpageCapacity = 10;
		poiInfos = new ArrayList<PoiInfo>();
		View view = LayoutInflater.from(this).inflate(R.layout.bdapi_marker,
				null);
		markTV = (TextView) view.findViewById(R.id.tv_marker);
	}

	/**
	 * 
	 * @Description: 初始化菜单
	 */
	private void initMenuFragment() {
		fragmentManager = getSupportFragmentManager();
		MenuParams menuParams = new MenuParams();
		int w = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		int h = View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED);
		topRL.measure(w, h);
		topHeight = topRL.getMeasuredHeight();
		menuParams.setActionBarSize(topHeight);
		menuParams.setMenuObjects(getMenuObjects());
		menuParams.setClipToPadding(false);
		menuParams.setClosableOutside(true);
		mMenuDialogFragment = ContextMenuDialogFragment.newInstance(menuParams);
		mMenuDialogFragment.setItemClickListener(this);
	}

	/**
	 * 
	 * @Description: 设置列表项
	 */
	private List<MenuObject> getMenuObjects() {
		List<MenuObject> menuObjects = new ArrayList<MenuObject>();
		int mColor = getResources().getColor(R.color.actionbar_color);
		// 关闭
		MenuObject close = new MenuObject();
		close.setResource(R.drawable.icon_menu_close);
		close.setBgColor(mColor);
		// 结果
		MenuObject resultMenu = new MenuObject("结果");
		resultMenu.setResource(R.drawable.icon_menu_result);
		resultMenu.setBgColor(mColor);
		resultMenu.setMenuTextAppearanceStyle(R.style.TextViewStyle);
		// 半径

		radiusMenu = new MenuObject("<" + mRadius + "米");
		radiusMenu.setResource(R.drawable.icon_menu_radius);
		radiusMenu.setBgColor(mColor);
		radiusMenu.setMenuTextAppearanceStyle(R.style.TextViewStyle);
		// 上一页
		MenuObject previousMenu = new MenuObject("上一页");
		previousMenu.setResource(R.drawable.icon_menu_page_previous);
		previousMenu.setBgColor(mColor);
		previousMenu.setMenuTextAppearanceStyle(R.style.TextViewStyle);
		// 下一页
		MenuObject nextMenu = new MenuObject("下一页");
		nextMenu.setResource(R.drawable.icon_menu_page_next);
		nextMenu.setBgColor(mColor);
		nextMenu.setMenuTextAppearanceStyle(R.style.TextViewStyle);

		menuObjects.add(close);
		menuObjects.add(resultMenu);
		menuObjects.add(radiusMenu);
		menuObjects.add(previousMenu);
		menuObjects.add(nextMenu);
		return menuObjects;
	}

	/**
	 * 
	 * @Description: 初始化弹框
	 */
	private void initDialog() {
		BaseAnimatorSet mBasIn = new BounceTopEnter();
		BaseAnimatorSet mBasOut = new SlideBottomExit();
		radioList = new ArrayList<String>();
		radioList.add("<500m");
		radioList.add("<1000m");
		radioList.add("<2000m");
		radioList.add("<3000m");
		MyDialogAdapter adapter = new MyDialogAdapter(this, radioList);
		radioDialog = new NormalListDialog(this, adapter);
		radioDialog.title("请选择搜索区域")//
				.showAnim(mBasIn)//
				.dismissAnim(mBasOut);//
		radioDialog.setOnOperItemClickL(new OnOperItemClickL() {
			@Override
			public void onOperItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				radioDialog.dismiss();
				switch (position) {
				case 0:
					mRadius = 500;
					break;
				case 1:
					mRadius = 1000;
					break;
				case 2:
					mRadius = 2000;
					break;
				case 3:
					mRadius = 3000;
					break;
				default:
					break;
				}
				mPage = 0;
				radiusMenu.setTitle("<" + mRadius + "m");
				searchNearby(mPage, mKeyWord, mRadius);// 搜索附近美食
			}
		});

		// Poi弹框
		poiDialog = new MaterialDialog(this);
		poiDialog.showAnim(mBasIn).dismissAnim(mBasOut);
		poiDialog.setCanceledOnTouchOutside(true);
		poiDialog.btnText("取消", "详情");
		poiDialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {
			@Override
			public void onBtnLeftClick() {
				poiDialog.dismiss();
			}
		});
		poiDialog.setOnBtnRightClickL(new OnBtnRightClickL() {

			@Override
			public void onBtnRightClick() {
				if (null == poiInfo || !poiInfo.hasCaterDetails) {
					poiDialog.dismiss();
					showToast("该美食暂无详情介绍~", false);
				} else {
					poiDialog.dismiss();
					Intent intent = new Intent(FoodActivity.this,
							FoodInfoActivity.class);
					intent.putExtra("poiInfo", poiInfo);
					startActivity(intent);
				}
			}
		});
	}

	/**
	 * 
	 * @Description: 初始化百度地图
	 */
	private void initMap() {
		mMapView.showScaleControl(false);
		mMapView.showZoomControls(false);
		mBaiduMap = mMapView.getMap();
		// 开启定位图层
		mBaiduMap.setMyLocationEnabled(true);
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
				MyLocationConfiguration.LocationMode.NORMAL, true, null));
		// 定位初始化
		mLocationClient = new LocationClient(this);
		mListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mListener);
		LocationClientOption option = new LocationClientOption();
		// 可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
		option.setLocationMode(LocationMode.Hight_Accuracy);
		// 设置坐标类型
		option.setCoorType("bd09ll");
		// 可选，默认false,设置是否使用gps
		option.setOpenGps(true);
		// 可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
		option.setScanSpan(60000);
		// 可选，设置是否需要地址信息，默认不需要
		option.setIsNeedAddress(true);
		// 可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
		option.setLocationNotify(true);
		// 可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
		option.setIsNeedLocationDescribe(true);
		// 可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
		option.setIsNeedLocationPoiList(true);
		// 可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
		option.setIgnoreKillProcess(false);
		// 可选，默认false，设置是否收集CRASH信息，默认收集
		option.SetIgnoreCacheException(false);
		// 可选，默认false，设置是否需要过滤gps仿真结果，默认需要
		option.setEnableSimulateGps(false);
		option.setNeedDeviceDirect(true);
		mLocationClient.setLocOption(option);

		// 初始化搜索模块，注册搜索事件监听
		mPoiSearch = PoiSearch.newInstance();
		mPoiSearch.setOnGetPoiSearchResultListener(this);
		manager = new MyOverlayManager(mBaiduMap);
		// 标记点击事件
		mBaiduMap.setOnMarkerClickListener(new OnMarkerClickListener() {

			@Override
			public boolean onMarkerClick(Marker marker) {
				if (lastMarker != null) {
					markTV.setText(lastMarker.getTitle());
					markTV.setBackgroundResource(R.drawable.icon_mark);
					BitmapDescriptor bitmap = BitmapDescriptorFactory
							.fromView(markTV);
					lastMarker.setIcon(bitmap);
				} else {

				}
				lastMarker = marker;
				String num = marker.getTitle();
				markTV.setText(num);
				markTV.setBackgroundResource(R.drawable.icon_focus_mark);
				BitmapDescriptor bitmap = BitmapDescriptorFactory
						.fromView(markTV);
				marker.setIcon(bitmap);
				poiInfo = marker.getExtraInfo().getParcelable("poiInfo");
				poiDialog.title(poiInfo.name);
				poiDialog.content("城市：" + poiInfo.city + "\n电话："
						+ poiInfo.phoneNum + "\n地址：" + poiInfo.address);
				poiDialog.show();
				return true;
			}
		});

		startLocation();// 开始定位
	}

	/**
	 * 
	 * @Description: 开始定位
	 */
	private void startLocation() {
		mLocationClient.start();// 开始定位
	}

	/**
	 * 
	 * @ClassName: 定位监听
	 */
	public class MyLocationListener implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null) {
				showToast("定位失败，请确认是否设置了定位权限~", false);
				return;
			}
			mLatLng = new LatLng(location.getLatitude(),
					location.getLongitude());
			if (isFirstLoc) {
				isFirstLoc = false;
				MyLocationData locData = new MyLocationData.Builder()
						.accuracy(location.getRadius())
						// 此处设置开发者获取到的方向信息，顺时针0-360
						.direction(100).latitude(location.getLatitude())
						.longitude(location.getLongitude()).build();
				mBaiduMap.setMyLocationData(locData);
				MapStatus.Builder builder = new MapStatus.Builder();
				builder.target(mLatLng).zoom(18.0f);
				mBaiduMap.animateMapStatus(MapStatusUpdateFactory
						.newMapStatus(builder.build()));
				searchNearby(mPage, mKeyWord, mRadius);
			}
		}

	}

	/**
	 * 
	 * @Description: 搜索附近美食
	 * @param: page
	 * @param: keyWord
	 * @param: distance
	 */
	private void searchNearby(int page, String keyWord, int radius) {
		dialog.show();
		PoiNearbySearchOption newrOption = new PoiNearbySearchOption();
		newrOption.keyword(keyWord);
		newrOption.location(mLatLng);
		newrOption.pageNum(page);
		newrOption.pageCapacity(mpageCapacity);// 设置单页容量
		newrOption.radius(radius);
		newrOption.sortType(PoiSortType.comprehensive);
		mPoiSearch.searchNearby(newrOption);
	}

	/**
	 * 
	 * @Description: 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.food_back_btn: {// 返回
			finish();
			break;
		}
		case R.id.food_more_btn: {// 更多
			if (fragmentManager
					.findFragmentByTag(ContextMenuDialogFragment.TAG) == null) {
				mMenuDialogFragment.show(fragmentManager,
						ContextMenuDialogFragment.TAG);
			}
			break;
		}
		default:
			break;
		}
	}

	/**
	 * 
	 * @Description: Poi搜索监听
	 */
	@Override
	public void onGetPoiResult(PoiResult result) {
		dialog.dismiss();
		if (result == null
				|| result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
			showToast("附近暂未找到美食~", true);
			return;
		}
		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			totalPage = result.getTotalPageNum();
			mBaiduMap.clear();
			if (null != poiInfos && 0 < poiInfos.size()) {
				poiInfos.clear();
			}
			poiInfos.addAll(result.getAllPoi());
			int i = 0;
			List<OverlayOptions> options = new ArrayList<OverlayOptions>();
			for (PoiInfo info : poiInfos) {
				markTV.setText((++i) + "");
				markTV.setBackgroundResource(R.drawable.icon_mark);
				BitmapDescriptor bitmap = BitmapDescriptorFactory
						.fromView(markTV);
				Bundle bundle = new Bundle();
				bundle.putParcelable("poiInfo", info);
				OverlayOptions overlayOptions = new MarkerOptions()
						.position(info.location).icon(bitmap).title(i + "")
						.extraInfo(bundle);
				options.add(overlayOptions);
			}
			manager.setData(options);
			manager.addToMap();
			manager.zoomToSpan();
			return;
		}
		if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {
			showToast("附近暂未找到美食~", true);
		}
	}

	/**
	 * 
	 * @Description: Poi详情搜索监听
	 */
	@Override
	public void onGetPoiDetailResult(PoiDetailResult result) {

	}

	/**
	 * 
	 * @Description: Toast显示信息
	 */
	private void showToast(String message, Boolean isInfo) {
		if (isInfo) {
			ToastUtils.showInfoToast(this, message, R.id.food_top_ll);
		} else {
			ToastUtils.showAlertToast(this, message, R.id.food_top_ll);
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		mMapView.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mLocationClient.stop();
		mMapView.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 退出时销毁定位
		mLocationClient.stop();
		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mPoiSearch.destroy();
		mMapView.onDestroy();
	}

	@Override
	public void onMenuItemClick(View clickedView, int position) {
		switch (position) {
		case 0: {// 关闭
			break;
		}
		case 1: {// 结果
			Intent intent = new Intent(this, FoodResultActivity.class);
			intent.putExtra("page", mPage);
			intent.putExtra("totalPage", totalPage);
			intent.putExtra("radius", mRadius);
			intent.putExtra("keyWord", mKeyWord);
			intent.putExtra("pageCapacity", mpageCapacity);
			intent.putExtra("location", mLatLng);
			startActivity(intent);
			break;
		}
		case 2: {// 半径
			radioDialog.show();
			radioDialog.getWindow().setGravity(Gravity.CENTER);
			break;
		}
		case 3: {// 上一页
			if (0 == mPage) {
				showToast("已是第一页~", true);
				return;
			}
			mPage--;
			searchNearby(mPage, mKeyWord, mRadius);// 搜索附近美食
			break;
		}
		case 4: {// 下一页
			if ((totalPage - 1) == mPage) {
				showToast("已是最后一页~", true);
				return;
			}
			mPage++;
			searchNearby(mPage, mKeyWord, mRadius);// 搜索附近美食
			break;
		}
		default:
			break;
		}
	}
}
